package com.isljj.web_chat2.config;

import com.isljj.web_chat2.constant.Constant;
import com.isljj.web_chat2.controller.WebsocketController;
import com.isljj.web_chat2.model.User;
import com.isljj.web_chat2.utils.CookieUtils;
import com.isljj.web_chat2.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.Map;

@EnableWebSocket
@Configuration
@Slf4j
public class WebSocketConfig implements WebSocketConfigurer {
    @Autowired
    WebsocketController websocketController;
    @Autowired
    CookieUtils cookieUtils;
    @Autowired
    JWTUtils jwtUtils;

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(websocketController,"/WebSocketMessage")
                .addInterceptors(new HandshakeInterceptor() {
                    @Override
                    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

                        String cookie = (request.getHeaders().get("cookie").get(0));
                        String jwtToken = cookieUtils.parseToken(cookie);
                        attributes.put("token",jwtToken);
                        //log.info("WebSocket - jwtToken - " + jwtToken);j
                        try {
                            jwtUtils.getUserByToken(jwtToken);
                        }catch (NullPointerException nullPointerException){
                            return false;
                        }
                        return true;
                    }

                    @Override
                    public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {

                    }
                });
    }
}
